package com.yxw.srpc.registry;

import com.yxw.srpc.helper.Constant;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by hp on 2016/5/11.
 */
public class ServiceRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class);
    private CountDownLatch latch = new CountDownLatch(1);

    private String registryAddress;

    public ServiceRegistry(String registryAddress){
        this.registryAddress = registryAddress;
    }

    public void register(String data){
        if(data != null){
            ZooKeeper zk = connectServer();
            if(zk != null){
                createNode(zk,data);
            }
        }
    }

    private ZooKeeper connectServer(){
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT,new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
                        latch.countDown();
                    }
                }
            });
            //latch.await();
        }catch (IOException e){
            LOGGER.error("", e);
        }
        return zk;
    }

    private void createNode(ZooKeeper zk,String data){
        String path = "";
        byte[] bytes = data.getBytes();
        try
        {
            path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        }
        catch ( KeeperException | InterruptedException e1)
        {
            try {
                LOGGER.info(path + " does not exist, creating");
                zk.create(Constant.ZK_REGISTRY_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
                System.out.println(path + "+++++++++++++++++++++++++" + data);
            } catch ( KeeperException | InterruptedException e2)
                {
                    e2.printStackTrace();
                    LOGGER.error("", e2);
                }
        }
    }

































}
